package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.Mapper.SessionMapper;
import com.example.demo.context.BaseContext;
import com.example.demo.entity.Session;
import com.example.demo.service.SessionService;
import com.example.demo.vo.sessionVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SessionServiceImpl extends ServiceImpl<SessionMapper, Session> implements SessionService {

    final SessionMapper sessionMapper;

    /*
    返回会话列表
     */
    @Override
    public List<sessionVO> getList(Long userId) {
        List<sessionVO> list=sessionMapper.getList(userId);
        return list;
    }

    @Override
    public Long createSession(Long mode) {
        Session session = new Session();
        session.setTag(0);
        session.setCreatedAt(LocalDateTime.now());
        session.setUserId(BaseContext.getCurrentId());
        //创建一个rag会话
        if(mode==1) {
            session.setTag(1);
        }else {
            //普通会话
            session.setTag(0);
        }
        sessionMapper.insert(session);
        return session.getId();
    }

    @Override
    public Long getOrCreateSessionByRoleId(Long roleId) {
        Long userId = BaseContext.getCurrentId();
        
        // 先查询是否已存在该用户与角色的会话
        Long existingSessionId = sessionMapper.getSessionIdByUserIdAndRoleId(userId, roleId);
        
        if (existingSessionId != null) {
            // 如果存在，直接返回
            return existingSessionId;
        } else {
            // 如果不存在，创建新的会话
            Session session = new Session();
            session.setUserId(userId);
            session.setRoleId(roleId);
            session.setTag(2); // 使用tag=2表示角色会话
            session.setCreatedAt(LocalDateTime.now());
            sessionMapper.insert(session);
            return session.getId();
        }
    }
}
